package com.qf.application.controller;


import com.qf.application.entity.User;
import com.qf.application.entity.vo.LoginVo;
import com.qf.application.utils.result.Result;
import com.qf.application.service.UserService;
import com.qf.application.utils.util.JwtUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author l
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource(name = "JsonRedisTemplate")
    private RedisTemplate  redisTemplate;

    private String loginKey = "loan:login:%s";

    @PostMapping("/register")
    public Result register(String username,String password){
        Boolean flag = userService.getUserByName(username);
        if(flag){
            User user =new User();
            user.setCreateTime(new Date());
            user.setUsername(username);
            user.setPassword(BCrypt.hashpw(password,BCrypt.gensalt()));
            userService.save(user);
        }

        return new Result(200,"注册成功",null);
    }

    @GetMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){
        User user2 = userService.getUserByNameAndPassword(user.getUsername(),user.getPassword());
        //User user1 = userService.getById(user.getId());
        //System.out.println("user1 = " + user1);

        String token  = JwtUtils.createToken(user2.getId(),user2.getUsername());
        String key = String.format(loginKey,token);

        System.out.println("user2 = " + user2);

        redisTemplate.opsForValue().set(key,user2.getId(),30, TimeUnit.MINUTES);

        //把token放入header中
        response.setHeader("g_token", token);


        LoginVo loginVo = new LoginVo(token,user2);

        return new Result(200,"登录成功",loginVo);
    }

    @PutMapping("/info")
    public Result getUserInfo(@RequestBody User user){

        Boolean b = userService.saveUserInfo(user);

        return Result.success(b,"信息录入成功");
    }

    @RequestMapping("/logout")
    public Result loginOut(HttpServletRequest request, HttpServletResponse response){
        String gToken = request.getHeader("g_token");
        String format = String.format(loginKey, gToken);
        //System.out.println("format = " + format);
        //删除key
        Boolean delete = redisTemplate.delete(format);


        return Result.success(delete,"退出登录");
    }

    @RequestMapping("setPassword")
    public Result ChangePassword(HttpServletRequest request,String oldPassword,String newPassword){

        //获取token
        String gToken = request.getHeader("g_token");

        //从redis中获取userId
        String format = String.format(loginKey, gToken);
        Long userId = (Long) redisTemplate.opsForValue().get(format);

        System.out.println("userId = " + userId);
        User user = userService.getById(userId);

        if(StringUtils.isEmpty(oldPassword)){
            throw new RuntimeException("原密码输入不能为空");
        }
        if(StringUtils.isEmpty(newPassword)){
            throw new RuntimeException("新密码不能为空");
        }

        if (!BCrypt.checkpw(oldPassword,user.getPassword())) {
            throw new RuntimeException("原密码输入错误");
        }
        if(oldPassword.equals(newPassword)){
            throw new RuntimeException("新密码与原密码一致");
        }

        //将新密码加盐
        String hashpw = BCrypt.hashpw(newPassword, BCrypt.gensalt());
        user.setPassword(hashpw);
        boolean b = userService.updateById(user);

        return Result.success(b,"设置密码成功");
    }

}
